﻿using System;
using System.IO;
using ImageMagick;
using Ayatta.Contract;
using System.Configuration;
using System.ServiceModel;
using Ayatta.Contract.Component;

namespace Ayatta.FileUpload.Server
{
    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.PerCall)]
    public class UploadService : IUploadService
    {
        /// <summary>
        /// 默认根目录
        /// </summary>
        private static readonly string RootFolder = ConfigurationManager.AppSettings["upload.rootfolder"] ?? "d:/upload/";

        /// <summary>
        /// 默认文件夹
        /// </summary>
        private static readonly string DefaultFolder = ConfigurationManager.AppSettings["upload.defaultfolder"] ?? "default";

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file">待上传文件</param>
        public void Upload(UploadFile file)
        {

            try
            {
                var filePath = CreateFolder(file);
                SaveFile(file.Data, filePath);
            }
            catch (Exception e)
            {
                Program.Logger.Warn(e.Message);
            }
        }

        public void ProductPropImageUpload(UploadFile file)
        {
            try
            {
                var filePath = CreateFolder(file);
                var extension = Path.GetExtension(filePath);
                using (var image = new MagickImage(file.Data))
                {
                    image.Resize(440, 440);
                    image.Write(filePath + ".l" + extension);
                    image.Resize(110, 110);
                    image.Write(filePath + ".s" + extension);
                    image.Resize(32, 32);
                    image.Write(filePath + ".xxs" + extension);
                }
            }
            catch (Exception e)
            {
                Program.Logger.Warn(e.Message);
            }
        }

        public void ProductItemImageUpload(UploadFile file)
        {
            try
            {
                var filePath = CreateFolder(file);
                var extension = Path.GetExtension(filePath);
                using (var image = new MagickImage(file.Data))
                {
                    if (file.Extra == "1")//主图片
                    {
                        if (image.Width >= 800 || image.Height >= 800)
                        {
                            image.Resize(800, 800);
                            image.Write(filePath + ".xl" + extension);
                        }

                        image.Resize(440, 440);
                        image.Write(filePath + ".l" + extension);

                        image.Resize(220, 220);
                        image.Write(filePath + ".m" + extension);

                        image.Resize(110, 110);
                        image.Write(filePath + ".s" + extension);

                        image.Resize(64, 64);
                        image.Write(filePath + ".xs" + extension);

                        image.Resize(32, 32);
                        image.Write(filePath + ".xxs" + extension);
                    }
                    else
                    {
                        if (image.Width >= 800 || image.Height >= 800)
                        {
                            image.Resize(800, 800);
                            image.Write(filePath + ".xl" + extension);
                        }

                        image.Resize(440, 440);
                        image.Write(filePath + ".l" + extension);

                        image.Resize(64, 64);
                        image.Write(filePath + ".xs" + extension);
                    }
                }
            }
            catch (Exception e)
            {
                Program.Logger.Warn(e.Message);
            }
        }

        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="file">文件夹名</param>
        private static string CreateFolder(UploadFile file)
        {
            var folder = file.Folder;
            var fileName = file.Name;

            if (folder == null) folder = DefaultFolder;
            if (!folder.EndsWith("/")) folder += "/";

            var uploadFolder = RootFolder + folder;
            try
            {
                if (!Directory.Exists(uploadFolder))
                {
                    Directory.CreateDirectory(uploadFolder);
                }
            }
            catch (Exception e)
            {
                Program.Logger.Warn(e.Message);
            }
            return Path.Combine(uploadFolder, fileName);
        }

        /// <summary>
        /// 保存上传的文件
        /// </summary>
        /// <param name="stream">文件数据流</param>
        /// <param name="file">文件名(包含路径)</param>
        private static void SaveFile(Stream stream, string file)
        {
            using (stream)
            using (var target = new FileStream(file, FileMode.Create, FileAccess.Write))
            {
                int count;
                const int bufferLen = 32768 * 2; //初始化一个64k的缓存
                var buffer = new byte[bufferLen];
                while ((count = stream.Read(buffer, 0, bufferLen)) > 0)
                {
                    target.Write(buffer, 0, count);
                }
            }
        }
    }
}